package com.minli.weixin.common.util;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by wangml on 2017/8/29.
 * 模拟redis环境
 */
public class JedisUtils {
    private static Map<String,String> cacheMap = new HashMap<>();

    /**
     * 设置值
     * @param key
     * @param value
     */
    public static void set(String key,String value){
        cacheMap.put(key,value);
    }

    /**
     * 获取值
     * @param key
     * @return
     */
    public static String get(String key){
        return cacheMap.get(key);
    }

    /**
     * 设置有效期的字符串缓存
     * @param key
     * @param value
     * @param seconds
     */
    public static void setex(String key, int seconds, String value) {
        cacheMap.put(key,value);
        generateTimer(key,seconds);
    }

    private static void generateTimer(String key, int delay){
        TimerTask tt = new RemoveTimerTask(key);
        new Timer().schedule(tt, delay);
    }

    static class RemoveTimerTask extends TimerTask {
        private String key;
        RemoveTimerTask(String key){
            this.key = key;
        }
        @Override
        public void run() {
            cacheMap.remove(key);
            System.out.println("remove cacheMap key=["+key+"]");
        }
    }

    public static void main(String[] args) {
        JedisUtils.setex("zhang",5000,"111111");

        System.out.println(JedisUtils.get("zhang"));
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(JedisUtils.get("zhang"));
    }
}
